package ay.shadow.core.utils;

import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.text.PDFTextStripper;

public class PDFReplaceExample {
    public static void main(String[] args) {
        try {
            // 加载PDF文档
            PDDocument document = PDDocument.load(new File("C:\\Users\\br\\Pictures\\test.pdf"));

            // 读取文件内容
            PDFTextStripper pdfStripper = new PDFTextStripper();
            String content = pdfStripper.getText(document);
            System.out.println("原PDF内容: " + content);

            // 替换文本
            String updatedContent = content.replace("Test01", "7788").replace("\n", "").replace("\r", "");;

            // 创建新的PDF文档
            PDDocument newDocument = new PDDocument();
            PDPage page = new PDPage();
            newDocument.addPage(page);
            PDPageContentStream contentStream = new PDPageContentStream(newDocument, page);

            // 在新文档中写入更新后的内容
            contentStream.beginText();
            contentStream.setFont(PDType1Font.HELVETICA, 12);
            contentStream.newLineAtOffset(100, 700);
            contentStream.showText(updatedContent);
            contentStream.endText();
            contentStream.close();

            // 保存新PDF文档
            newDocument.save("updated.pdf");
            newDocument.close();
            document.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
